﻿using System.Net;
using Newtonsoft.Json.Linq;

namespace AjaxChatService.YahooMessenger
{
    public class GetSessionHepler
    {
        public string RequestServer
        {
            get { return YMConstants.DevUrl; }
        }
        public YMAuthentication Authentication { get; set; }

        public string SessionId;

        public void ExecuteRequest()
        {
            //  Create the HTTP URL
            var uri = "http://" + RequestServer + //"developer.messenger.yahooapis.com" +
                            YMConstants.SessionManagementUrl
                            + "?" + Authentication.GetOAuthParameters();

            WebRequest request = WebRequest.Create(uri);
            request.ContentType = "application/json; charset=utf-8";

            //var responseStr = HttpUtils.SendHttpGet(request, Authentication);
            var responseStr = HttpUtils.SendHttpPost(request, Authentication, "{}");
            JObject result = JObject.Parse(responseStr);

            if (result == null)
                throw new MessengerException(MessengerException.UNKNOWN_SERVER_ERROR, "Unknown server error");

            UnserializeJSONResponseParameters(result);
        }

        private void UnserializeJSONResponseParameters(JObject o)
        {
            SessionId = o["sessionId"].ToString();
        }
    }
}